package com.maoning.gulimallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.maoning.common.to.es.SkuEsModel;
import com.maoning.common.utils.R;
import com.maoning.gulimallsearch.constant.EsConstant;
import com.maoning.gulimallsearch.feign.ProductFeignService;
import com.maoning.gulimallsearch.service.MallSearchService;
import com.maoning.gulimallsearch.service.ProductSaveService;
import com.maoning.gulimallsearch.vo.AttrResponseVo;
import com.maoning.gulimallsearch.vo.BrandVo;
import com.maoning.gulimallsearch.vo.SearchParam;
import com.maoning.gulimallsearch.vo.SearchResult;
import com.zaxxer.hikari.util.ClockSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @Author : 猫宁
 * @Date: 2022/2/11
 */
@Service
@Slf4j
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    private ProductFeignService productFeignService;


    @Override
    public SearchResult search(SearchParam searchParam) {
        SearchResult result = null;
        //准备检索请求
        final SearchRequest searchRequest = buildSearchRequest(searchParam);
        //执行检索请求
        try {
            final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            //分析响应数据封装成我们需要的格式
            result = buildSearchResult(searchParam,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构件结果数据
     *
     * @param searchParam
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchParam searchParam, SearchResponse response) {
        final SearchResult result = new SearchResult();
        final SearchHits hits = response.getHits();
        final SearchHit[] searchHits = hits.getHits();
        if(!CollectionUtils.isEmpty(Arrays.asList(searchHits))){
            final List<SkuEsModel> products = Arrays.stream(searchHits).map(hit -> {
                final String sourceAsString = hit.getSourceAsString();
                final SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                final HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                if(skuTitle != null){
                    final String skuTitleString = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitleString);
                }
                return skuEsModel;
            }).collect(Collectors.toList());
            result.setProducts(products);
        }

        //聚合信息
        final Aggregations aggregations = response.getAggregations();

        final ParsedNested attr_agg = aggregations.get("attr_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        final ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        final List<? extends Terms.Bucket> attrIdBuckets = attr_id_agg.getBuckets();
        attrIdBuckets.forEach(attrIdBucket -> {
            final SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            final long attrId = attrIdBucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);
            final ParsedStringTerms attr_name_agg = attrIdBucket.getAggregations().get("attr_name_agg");
            final String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            final ParsedStringTerms attr_value_agg = attrIdBucket.getAggregations().get("attr_value_agg");
            final List<String> attrValues = attr_value_agg.getBuckets().stream().map(attr_value -> {
                return attr_value.getKeyAsString();
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        });


        result.setAttrs(attrVos);

        final ParsedLongTerms brand_agg = aggregations.get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        final List<? extends Terms.Bucket> brandBuckets = brand_agg.getBuckets();
        brandBuckets.forEach(brandBucket -> {
            final long brandId = brandBucket.getKeyAsNumber().longValue();
            final SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            brandVo.setBrandId(brandId);
            //获取其中的子聚合
            final ParsedStringTerms brand_img_agg = brandBucket.getAggregations().get("brand_img_agg");
            if(brand_img_agg.getBuckets().get(0) != null){
                final String brand_img = brand_img_agg.getBuckets().get(0).getKeyAsString();
                brandVo.setBrandImg(brand_img);
            }
            final ParsedStringTerms brand_name_agg = brandBucket.getAggregations().get("brand_name_agg");
            if(brand_img_agg.getBuckets().get(0) != null){
                final String brand_name = brand_name_agg.getBuckets().get(0).getKeyAsString();
                brandVo.setBrandName(brand_name);
            }
            brandVos.add(brandVo);
        });
        result.setBrands(brandVos);

        final ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        final List<? extends Terms.Bucket> catalogBuckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : catalogBuckets) {
            final SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //分类id
            catalogVo.setCatalogId(Long.valueOf(bucket.getKeyAsString()));
            //分类名字
            final ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            final String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        result.setPageNum(searchParam.getPageNum());
        final long total = hits.getTotalHits().value;
        result.setTotal(total);
        final long l = total % EsConstant.PRODUCT_PAGESIZE == 0 ? total / EsConstant.PRODUCT_PAGESIZE : total / EsConstant.PRODUCT_PAGESIZE + 1;
        result.setTotalPages(l);

        List<Integer> pageNavs = new ArrayList<>();
        final Long totalPages = result.getTotalPages();
        for (int i = 1; i < totalPages + 1; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        //构建面包屑导航
        if(!CollectionUtils.isEmpty(searchParam.getAttrs())){
            List<SearchResult.NavVo> navVos = new ArrayList<>();
            final List<SearchResult.NavVo> navVoList = searchParam.getAttrs().stream().map(attr -> {
                final SearchResult.NavVo navVo = new SearchResult.NavVo();
                //这里的attr类似这样:   attrs=2_5寸:6寸
                final String[] s = StringUtils.split(attr, "_");
                navVo.setNavVoValue(s[1]);
                //这样以后,s[0]就是属性的id
                final R attrInfo = productFeignService.attrInfo(Long.valueOf(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if(attrInfo.getCode() == 200){
                    final AttrResponseVo attrResponseVo = attrInfo.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavVoName(attrResponseVo.getAttrName());

                }else {
                    navVo.setNavVoName(s[0]);
                }
                final String replace = replaceQueryString(searchParam,attr,"attrs");
                navVo.setNavVoLink("http://search.gulimall.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());
            result.setNavVos(navVoList);
        }

        //品牌,分类
        if(searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0){
            final List<SearchResult.NavVo> navVos = result.getNavVos();
            final SearchResult.NavVo navVo = new SearchResult.NavVo();

            navVo.setNavVoName("品牌");
            final R r = productFeignService.brandInfos(searchParam.getBrandId());
            if(r.getCode() == 0){
                final List<BrandVo> brands = r.getData("brands", new TypeReference<List<BrandVo>>() {
                });
                final StringBuffer stringBuffer = new StringBuffer();
                String replace = "";
                for (BrandVo brand : brands) {
                    final String brandName = brand.getName();
                    stringBuffer.append(brandName).append(";");
                    replace = replaceQueryString(searchParam,brand.getBrandId().toString(),"brandId");
                }
                navVo.setNavVoValue(stringBuffer.toString());
                navVo.setNavVoLink("http://search.gulimall.com/list.html?" + replace);
            }
            navVos.add(navVo);
        }

        //// TODO: 2022/2/27 菜单分类也可以加上,而且菜单不需要取消


        //取消了面包屑以后,我们要跳转到哪个地方?

        log.info("构建的响应结果为:{}",result.getAttrs());
        return result;
    }

    private String replaceQueryString(SearchParam searchParam, String value,String key) {
        //把请求vo里的queryString拿出来做一个替换,放进link
        final String queryString = searchParam.getQueryString();
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+", "%20").replace("%28", "(").replace("%29", ")");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String replace = queryString.replace("&" + key + "=" + encode, "").replace("attrs=" + encode, "");
        log.info("replace====>{},encode==>{}",replace,encode);
        return replace;
    }

    /**
     * 封装检索请求
     * @return
     * @param searchParam
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//构件DSL执行语句
        //模糊匹配,过滤
        final BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if(StringUtils.isNotEmpty(searchParam.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }
        //分类id
        if(searchParam.getCatalog3Id() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }
        //品牌id
        if(searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
        if(!CollectionUtils.isEmpty(searchParam.getAttrs())){
            //attr=1_5寸&attr=2_16G:8G
            searchParam.getAttrs().forEach(attr -> {
                final BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                final String[] s = StringUtils.split(attr, "_");
                String attrId = s[0];
                String[] attrValues = StringUtils.split(s[1],":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                final NestedQueryBuilder attrsNestedQueryBuilder = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQueryBuilder.filter(attrsNestedQueryBuilder);
            });
        }


        //是否有库存
        if(searchParam.getHasStock() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",searchParam.getHasStock() == 1));
        }

        if(StringUtils.isNotEmpty(searchParam.getSkuPrice())){
            final RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            final String[] split = StringUtils.split(searchParam.getSkuPrice(), "_");
            if(split.length == 2){
                rangeQueryBuilder.gte(split[0]).lte(split[1]);
            }else {
                if(StringUtils.startsWith(searchParam.getSkuPrice(), "_")){
                    rangeQueryBuilder.lte(split[0]);
                }else {
                    rangeQueryBuilder.gte(split[0]);
                }
            }

            boolQueryBuilder.filter(rangeQueryBuilder);
        }


        searchSourceBuilder.query(boolQueryBuilder);
        //排序,分页,高亮

        //sort=hotScore_asc/desc
        if(StringUtils.isNotEmpty(searchParam.getSort())){
            final String[] s = StringUtils.split(searchParam.getSort(), "_");
            final SortOrder order = SortOrder.fromString(s[1]);
            searchSourceBuilder.sort(s[0], order);
        }

        //分页
        //pageNum:1 from:0 size:5 [0,1,2,3,4]
        //pageNum:2 from:1 size:5
        //from = (pageNum - 1)*size
        searchSourceBuilder.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //高亮
        if(StringUtils.isNotEmpty(searchParam.getKeyword())){
            final HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }
        //聚合分析
        //品牌聚合
        final TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId");
        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brand_agg);

        //分类聚合 catalog_agg
        final TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalog_agg);

        //属性聚合
        final NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        final TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName"));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue"));
        attr_agg.subAggregation(attr_id_agg);
        searchSourceBuilder.aggregation(attr_agg);



        log.info("构建的DSL语句为:{}",searchSourceBuilder);
        final SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},searchSourceBuilder);

        return searchRequest;
    }


}
